package com.hengpeng.itfin.job.activity;

import java.util.Date;
import java.util.List;

import com.hengpeng.common.cis.ComponentContextLoader;
import com.hengpeng.common.configuration.ConfigProvider;
import com.hengpeng.common.configuration.ConfigProviderFactory;
import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.scheduling.AbstractJob;
import com.hengpeng.common.scheduling.ScheduleConfig;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.common.util.MoneyUtil;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfin.common.SystemConfigUtil;
import com.hengpeng.itfin.service.ServiceFactory;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.SystemConfigConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.en.AccountType;
import com.hengpeng.itfinbase.en.RewardAddRateStatus;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.message.partner.TransferRequest;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.RewardAddRate;
import com.hengpeng.itfinbase.persist.UserInfo;

/**
 * 加息支付定时作业
 * 
 * @author weiyuan
 *
 */
public class RewardAddRatePayJob extends AbstractJob {

    private ServiceFactory serviceFactory = ComponentContextLoader.getBean(ServiceFactory.class);
    public final static ConfigProvider<String> cp = ConfigProviderFactory
            .getInstance(Constant.HP_COMMON_PROPERTIES_FILEPATH);

    public String page_return_url = cp.getConfigByPrimaryKey("page.return.url");

    public String service_notify_url = cp.getConfigByPrimaryKey("service.notify.url");

    private static final int fetchSize = 100;// 一次性批处理数量

    private static final String MDT000001 = "MDT000001";// 托管子账户名

//    private static final int poolSize = 30;// 定义线程池大小

    @Override
    public void exec(boolean isTimeout, ScheduleConfig config) {
        log.info("加息支付定时作业开始,时间：" + DateTimeUtil.formatToStr(new Date(), DateTimeUtil.DATE_FORMAT_YMDHMS));

        List<RewardAddRate> unpayList = serviceFactory.getDaoFactory().getRewardAddRateDao()
                .findRewardAddRateByStatus(RewardAddRateStatus.UNPAY, fetchSize);
        if (unpayList != null && unpayList.size() > 0) {
//            PoolServer poolServer = new PoolServer(poolSize);
            for (final RewardAddRate addbate : unpayList) {
//                poolServer.executeTask(new Runnable() {
//                    public void run() {
                        int i = serviceFactory.getRewardAddRateService().updateStatus(addbate.getId(),
                                RewardAddRateStatus.UNPAY, RewardAddRateStatus.PAID, new Date());
                        if (i > 0) {
                            /**
                             * 入账账户
                             */
                            UserInfo inuserinfo = serviceFactory.getDaoFactory().getUserInfoDao()
                                    .get(addbate.getUserId());
                            Account inAccount = serviceFactory.getDaoFactory().getAccountDao()
                                    .getAccountByUserId(inuserinfo.getId());
                            if (inAccount != null && !StringHelper.isEmpty(inAccount.getTrustAccountId())) {
                                /**
                                 * 出账账户
                                 */
                                UserInfo outUser = serviceFactory
                                        .getDaoFactory()
                                        .getUserInfoDao()
                                        .get(Long.parseLong(SystemConfigUtil
                                                .getConfigValue(SystemConfigConstants.PARTNER_USERID)));
                                Account outAccount = serviceFactory.getDaoFactory().getAccountDao()
                                        .getAccountByUserIdAndSub(outUser.getId(), MDT000001);

                                TransferRequest transferRequest = new TransferRequest();
                                transferRequest.setOutType(AccountType.PLATFORM);// 固定出账户只能是平台账户
                                transferRequest.setOutUserId(outUser.getId());
                                transferRequest.setOutCustId(outAccount.getTrustAccountId());
                                transferRequest.setOutAcctId(outAccount.getSubAccountId());
                                transferRequest.setInType(AccountType.PERSONAL);
                                transferRequest.setInUserId(inuserinfo.getId());
                                transferRequest.setInCustId(inAccount.getTrustAccountId());
                                transferRequest.setInAcctId(inAccount.getSubAccountId());
                                transferRequest.setTransAmt(MoneyUtil.convertFenToYuan(addbate.getMoney().longValue()));
                                transferRequest.setPartnerTransType(PartnerTransType.Transfer);
                                transferRequest.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
                                transferRequest.setBgRetUrl(service_notify_url);
                                transferRequest.setRetUrl(page_return_url);
                                transferRequest.setMerPriv("ADDREBATE");
                                ResponseMessage response = serviceFactory.getPartnerService().request(transferRequest);
                                if (!RespCodeConstants.CommonCode.TRANS_SUC.equals(response.getRespCode())) {
                                    /**
                                     * 返利失败还原状态
                                     */
                                    serviceFactory.getRewardAddRateService().updateStatus(addbate.getId(),
                                            RewardAddRateStatus.PAID, RewardAddRateStatus.UNPAY, new Date());
                                } else {
                                    log.info("用户[id=" + addbate.getUserId() + "]返利成功,返利金额["
                                            + MoneyUtil.convertFenToYuan(addbate.getMoney().longValue()) + "].");
                                }
                            } else {
                                /**
                                 * 还原状态
                                 */
                                serviceFactory.getRewardAddRateService().updateStatus(addbate.getId(),
                                        RewardAddRateStatus.PAID, RewardAddRateStatus.UNPAY, new Date());
                                log.info("用户[id=" + addbate.getUserId() + "]还没开通托管账户,暂时不能支付加.");
                            }
                        }
                    }
//                });
//            }
//            poolServer.endServer();
        }
        log.info("加息支付定时作业结束,时间：" + DateTimeUtil.formatToStr(new Date(), DateTimeUtil.DATE_FORMAT_YMDHMS));
    }
}
